/*
 *  Gurr - A multiprotocol chat client for Android
 *  Copyright (C) 2011 Malte Aschermann, Wilfried Ramaker
 *  
 *  This file is part of Gurr.
 *  
 *  Gurr is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  Gurr is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *  
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Gurr.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.masc.gurr.view.adapter;

import java.util.List;

import com.masc.gurr.Controller;
import com.masc.gurr.R;
import com.masc.gurr.model.Contact;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

public class ChatAdapter extends ArrayAdapter<Contact> {

	private List<Contact> items;

	public ChatAdapter(Context context, int textViewResourceId, List<Contact> cont_list) {
		super(context, textViewResourceId, cont_list);
		this.items = cont_list;
	}

	@Override
	public View getView(int position, View view, ViewGroup parent) {
		if (view == null) {
			LayoutInflater li = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = li.inflate(R.layout.chat_list_row, null);
			
		}
		Contact contact = items.get(position);
		if (contact != null) {
			TextView btOpenChat = (Button) view.findViewById(R.id.btOpenChat);
			TextView tvUid = (TextView) view.findViewById(R.id.chat_uid);
			Button btCloseChat = (Button) view.findViewById(R.id.btCloseChat);
			
			if (btOpenChat != null) {
				btOpenChat.setText(contact.getName());
				btOpenChat.setOnClickListener(new View.OnClickListener() {
		            public void onClick(View v) {
		            	String uid = ((TextView) ((View)v.getParent()).findViewById(R.id.chat_uid)).getText().toString();
		            	Controller.getInstance().chatWith(uid);
		            }
		        });
			}
			if(tvUid != null){
				tvUid.setText(contact.getUin());
			}
			if(btCloseChat != null){
				btCloseChat.setOnClickListener(new View.OnClickListener() {
		            public void onClick(View v) {
		            	String uid = ((TextView) ((View)v.getParent()).findViewById(R.id.chat_uid)).getText().toString();
		            	Controller.getInstance().removeChat(uid);
		            }
		        });
			}
		}
		return view;
	}
}
